import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Input, Select, Button, Card, InputNumber, Checkbox, Radio, Modal } from 'antd';
import { encode } from '@/utils/AesUtil';

const FormItem = Form.Item;
const InputGroup = Input.Group;
const CheckboxGroup = Checkbox.Group;
const CharacterOptions = ['数字', '大写字母', '小写字母', '特殊字符'];

@connect(({ pswPolicy, loading }) => ({
  pswPolicy,
  loading: loading.models.pswPolicy,
}))
@Form.create()
class PswPolicy extends PureComponent {
  handleSubmit = e => {
    const { dispatch, form } = this.props;
    e.preventDefault();
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.update(values);
      }
    });
  };

  // 提交
  update = async e => {
    const { dispatch } = this.props;
    const zifu = e.zifu.join();
    const values = {
      hasNumber: await encode(zifu.indexOf('数字') > -1 ? 1 : '0'),
      hasUpper: await encode(zifu.indexOf('大写字母') > -1 ? 1 : '0'),
      hasLower: await encode(zifu.indexOf('小写字母') > -1 ? 1 : '0'),
      hasSpecial: await encode(zifu.indexOf('特殊字符') > -1 ? 1 : '0'),
      continuousLength: await encode(parseInt(e.continuousLength)),
      hasUserName: await encode(parseInt(e.hasUserName)),
      isWeakPwdCheck: await encode(parseInt(e.isWeakPwdCheck)),
      historyPwdTime: await encode(parseInt(e.historyPwdTime)),
      minLength: await encode(parseInt(e.minLength)),
      maxLength: await encode(parseInt(e.maxLength)),
      validDays: await encode(parseInt(e.validDays)),
      notifyDays: await encode(parseInt(e.notifyDays)),
    };

    dispatch({
      type: 'pswPolicy/update',
      payload: values,
      callback: res => {
        if (res.result == 'ok') {
          Modal.success({ title: res.msg });
          this.pageList();
        } else {
          Modal.error({ title: '操作失败', content: res.msg });
        }
      },
    });
  };

  // 查询
  pageList() {
    const { dispatch } = this.props;
    dispatch({
      type: 'pswPolicy/queryList',
    });
  }

  componentDidMount() {
    this.pageList();
  }

  handleValidator = (rule, val, callback) => {
    const {
      form: { getFieldDecorator, getFieldValue },
    } = this.props;
    if (!val) {
      callback();
    }
    if (getFieldValue('validDays') < val) {
      callback('用户密码有效期的天数不应该小于密码过期前的天数');
    }
    callback();
  };

  pswLength = (rule, val, callback) => {
    const {
      form: { getFieldDecorator, getFieldValue },
    } = this.props;
    if (!val) {
      callback();
    }
    if (getFieldValue('maxLength') < val) {
      callback('密码最大长度应该大于最小长度');
    }
    callback();
  };

  render() {
    const {
      form: { getFieldDecorator, getFieldValue },
      submitting,
      pswPolicy: { data },
    } = this.props;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };
    const zifuD = [];
    if (data.hasNumber) {
      zifuD.push('数字');
    }
    if (data.hasUpper) {
      zifuD.push('大写字母');
    }
    if (data.hasLower) {
      zifuD.push('小写字母');
    }
    if (data.hasSpecial) {
      zifuD.push('特殊字符');
    }
    return (
      <Card bordered={false}>
        <Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }}>
          <FormItem {...formItemLayout} label="密码长度：">
            {getFieldDecorator('minLength', {
              rules: [
                { required: true, message: '密码长度不能为空' },
                { validator: this.pswLength },
              ],
              initialValue: (data && data.minLength) || '',
            })(<InputNumber min={6} max={32} />)}
            <span>&nbsp;~&nbsp;</span>
            {getFieldDecorator('maxLength', { initialValue: (data && data.maxLength) || '' })(
              <InputNumber min={6} max={32} />
            )}
          </FormItem>

          <FormItem {...formItemLayout} label="密码包含字符：">
            {getFieldDecorator('zifu', { initialValue: zifuD })(
              <CheckboxGroup options={CharacterOptions} />
            )}
          </FormItem>

          <FormItem {...formItemLayout} label="可否包含用户名：">
            <div>
              {getFieldDecorator('hasUserName', {
                initialValue: data && (data.hasUserName == 1 ? '1' : '0'),
              })(
                <Radio.Group>
                  <Radio value="0">不可以</Radio>
                  <Radio value="1">可以</Radio>
                </Radio.Group>
              )}
            </div>
          </FormItem>

          <FormItem {...formItemLayout} label="连续字符：">
            <span className="ant-form-text">不能包含</span>
            {getFieldDecorator('continuousLength', {
              rules: [{ required: true, message: '连续字符包含不能为空' }],
              initialValue: (data && data.continuousLength) || 3,
            })(<InputNumber min={3} max={10} />)}
            <span className="ant-form-text">位以上的连续数字或字母（包括倒序）</span>
          </FormItem>

          <FormItem {...formItemLayout} label="弱密码校验：">
            <div>
              {getFieldDecorator('isWeakPwdCheck', {
                initialValue: data && (data.isWeakPwdCheck == 1 ? '1' : '0'),
              })(
                <Radio.Group>
                  <Radio value="1">是</Radio>
                  <Radio value="0">否</Radio>
                </Radio.Group>
              )}
            </div>
          </FormItem>

          <FormItem {...formItemLayout} label="历史密码检验：">
            <span className="ant-form-text">最近</span>
            {getFieldDecorator('historyPwdTime', {
              rules: [{ required: true, message: '历史密码检验不能为空' }],
              initialValue: (data && data.historyPwdTime) || '',
            })(<InputNumber placeholder="1/2" min={1} max={2} />)}
            <span className="ant-form-text">次历史密码不能使用</span>
          </FormItem>

          <FormItem {...formItemLayout} label="密码有效期：">
            {getFieldDecorator('validDays', {
              initialValue: (data && data.validDays) || '',
            })(<InputNumber placeholder="" min={1} step={5} max={999} />)}
            <span className="ant-form-text">天</span>
          </FormItem>

          <FormItem {...formItemLayout} label="密码修改：">
            <span className="ant-form-text">密码过期前</span>
            {getFieldDecorator('notifyDays', {
              rules: [
                { required: true, message: '密码过期前天数不能为空' },
                {
                  validator: this.handleValidator,
                },
              ],
              initialValue: (data && data.notifyDays) || 0,
            })(<InputNumber min={1} />)}
            <span className="ant-form-text">天提醒</span>
          </FormItem>

          <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
            <Button type="primary" htmlType="submit" loading={submitting}>
              提交
            </Button>
            {
              // <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              //     重置
              // </Button>
            }
          </FormItem>
        </Form>
      </Card>
    );
  }
}

export default PswPolicy;
